package com.lottery.ruok.lottrey.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.adapter.YiLouAdapter;
import com.lottery.ruok.lottrey.dialog.YiLouLotteryBuyDialog;
import com.lottery.ruok.lottrey.eventbusObject.ChangLongRefrash;
import com.lottery.ruok.lottrey.eventbusObject.StartPrzePush;
import com.lottery.ruok.lottrey.retrofitModule.request.CreateOrderRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.CreateOrderResponse;
import com.lottery.ruok.lottrey.retrofitModule.request.GetYiLouRequest;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.response.YiLouResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ui.IToastAddBet;
import utils.Utils;

/**
 * 作者：lm
 * <p>
 * 创建日期：2018/8/20$
 * <p>
 * 描述：遗漏Fragment
 */
public class YiLouFragment extends BaseFragment implements YiLouLotteryBuyDialog.Callback {
    @BindView(R.id.rc_chang_long)
    RecyclerView rcChangLong;
    @BindView(R.id.no_net_viewstub)
    ViewStub noNetViewstub;

    private YiLouAdapter adapter;
    private String lotteryCode;
    private YiLouLotteryBuyDialog dialog;
    private List<YiLouResponse> yiLouList = new ArrayList<>();
    private int currentItem;
    private String perMoney;
    private View emptyLayout;
    private int notifyPosion=-1;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(ChangLongRefrash event) {
        getYiLouData(false);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_chang_long, null);

        ButterKnife.bind(this, view);

        init();

        return view;
    }

    private void init() {
        rcChangLong.setLayoutManager(new LinearLayoutManager(getContext()));
        rcChangLong.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        lotteryCode = getActivity().getIntent().getStringExtra("code");
        dialog = new YiLouLotteryBuyDialog(getContext(), R.layout.dialog_yi_lou_buy, this);
        getYiLouData(true);
        View view = noNetViewstub.inflate();
        emptyLayout = view.findViewById(R.id.no_net_view);
        emptyLayout.setBackgroundResource(R.color.bg_grey);
        emptyLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getYiLouData(true);
            }
        });
    }

    private void getYiLouData(final boolean showDialog) {
        RetrofitBase.getRetrofit().create(GetYiLouRequest.class).getResult(lotteryCode,UserInfo.getToken())
                .compose(RxHelper.<ArrayList<YiLouResponse>>handleResult())
                .subscribe(new RxSubscribe<ArrayList<YiLouResponse>>(getContext()) {
                    @Override
                    protected void _onNext(ArrayList<YiLouResponse> yiLouResponses) {
                        if (yiLouResponses != null && yiLouResponses.size() > 0) {
                            rcChangLong.setVisibility(View.VISIBLE);
                            noNetViewstub.setVisibility(View.GONE);
                            yiLouList.clear();
                            yiLouList.addAll(yiLouResponses);
                            adapter = new YiLouAdapter(getContext(), yiLouList);
                            rcChangLong.setAdapter(adapter);
                            adapter.setYiLouClickListener(new YiLouAdapter.yiLouClickListener() {
                                @Override
                                public void onYiLouClick(int posion, int v, String money) {
                                    if ("".equals(money)) {
                                        if (notifyPosion != -1 && notifyPosion != posion) {
                                            adapter.notifyItemChanged(notifyPosion);
                                        }
                                        notifyPosion = posion;
                                    } else {
                                        if (v == 1) {
                                            //显示弹窗
                                            if (UserInfo.getToken().equals("")) {
                                                Utils.showToast("请您先登录");
                                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                                startActivity(intent);
                                                getActivity().overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
                                            } else {
                                                perMoney = money;
                                                currentItem = posion;
                                                dialog.show();
                                                dialog.setDta(yiLouList.get(posion).getOff_name(), money);
                                            }

                                        }
                                    }
                                }
                            });
                        } else {
                            //显示没有数据的
                            rcChangLong.setVisibility(View.GONE);
                            noNetViewstub.setVisibility(View.VISIBLE);


                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        rcChangLong.setVisibility(View.GONE);
                        noNetViewstub.setVisibility(View.VISIBLE);
                    }

                    @Override
                    protected boolean showDialog() {
                        return showDialog;
                    }
                });
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

         EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void callback(int data) {
        switch (data) {
            case 1:
                dialog.dismiss();
                break;
            case 2:
                dialog.dismiss();
                sendMoney();
                break;
        }
    }

    private void sendMoney() {
        YiLouResponse bean = yiLouList.get(currentItem);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("rule_id", bean.getRule_id());
            jsonObject.put("pick_number", bean.getOff_num());
            jsonObject.put("position", "");
            jsonObject.put("amount_per_note", Integer.parseInt(perMoney));
            jsonObject.put("note_count", 1);
            jsonObject.put("odds", bean.getDan_odds());
            if (bean.getMax_rakeback() != null && !bean.getMax_rakeback().equals("")) {
                jsonObject.put("rakeback", bean.getMax_rakeback());
            } else {
                jsonObject.put("rakeback", "0");
            }
            jsonObject.put("is_follow", 0);
            jsonObject.put("is_win_stop", 0);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        jsonArray.put(jsonObject);
        RetrofitBase.getRetrofit().create(CreateOrderRequest.class).getResult(jsonArray, UserInfo.getToken(), null)
                .compose(RxHelper.<CreateOrderResponse>handleResult())
                .subscribe(new RxSubscribe<CreateOrderResponse>(getActivity()) {
                    @Override
                    protected void _onNext(CreateOrderResponse createOrderResponse) {
                        IToastAddBet.show(getActivity().getApplicationContext());
                        Utils.showToast("余额为" + createOrderResponse.getAfter_amount() + "元");
                        adapter.notifyItemChanged(currentItem);
                    }

                    @Override
                    public boolean showDialog() {
                        return true;
                    }
                });
    }
}

